#File: rondamon_http_server.py - HTTP Server for the Rondamon framework
#JGordon & Co

import socket
import os.path
from rdhtml_generator import process_file
from rondamon_interpreter import interpret2string
from random import random

Configuracion= {
    'puerto': 0,
    'dir': ""
    }

output_header = \
'''HTTP/1.0 200 OK
Content-type: %s

'''

page404 = \
'''HTTP/1.0 404 Not Found
Content-type: text/html

<h1>Error 404 Page Not Found</h1>
The page you have requested has not been found!
'''

page405 = \
'''HTTP/1.0 405 Method Not Allowed
Content-type: text/html

<h1>Method Not Allowed</h1>
Allowed Methods :
<br>GET
<br>POST
'''

page500 = \
'''HTTP/1.0 500 An Error has ocurred
Content-type: text/html

<h1>Error 500 An error ocurred while processing your request</h1>
Error: %s
'''

Cookie_string = 'Set-Cookie: id = %s '

Sessions = {}

extensiones = {
    'css':      'text/css',
    'html':     'text/html',
    'rdhtml':   'text/html',
    'jpeg':      'image/jpeg',
    'png':      'image/png',
    'gif':      'image/gif'
}

def configurar():
    print "Archivo de configuracion :"
    config_file = "conf.txt"#str(raw_input())
    if (os.path.exists(config_file) and  os.path.isfile(config_file)):
        f = open(config_file, "r")
        config = f.read()
        config = config.replace('\r\n', '\n').split('\n')
        for ind in config:
            a = ind.split(" ")
            Configuracion["puerto"] = a[0]
            Configuracion["dir"]= a[1]
        print "Port: ", Configuracion['puerto'], "\nPath: ", Configuracion['dir']  
  
  
def generate_id():
    return int(random()*10000)

def crear_conexion():

     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     sock.bind(('', int(Configuracion["puerto"])))
     sock.listen(1)

     try:
         while True:    
             print "Rondamon server... waiting connection..."        
             new_sock, address = sock.accept()        
             print "Conectado:", address       
             try:
                 entrada = new_sock.recv(2 ** 20).replace('\r\n', '\n').split('\n')
                 metodo, recurso, protocolo = entrada[0].split()
                 if metodo != 'GET' and metodo != 'POST':
                    new_sock.send(page405)
                 if recurso == '/':
                    recurso = '/index.html'
                 ruta = Configuracion ['dir'] + recurso
                 ruta = ruta.split('?')[0] #divide la ruta en caso de traer parametros
                 ########parameters - headers############################
                 parameters = []
                 headers = []

                 whitel_pos = entrada.index('') + 1
                 headers = entrada[1:whitel_pos-1]
                 if metodo == 'POST':
                    paramlist = entrada[whitel_pos:]
                    parameters = paramlist[0].split('&') #try except probably needed
                 elif metodo == 'GET':
                    try:
                        x, var = recurso.split('?')
                        parameters = var.split('&')
                    except Exception,e:
                        pass
                 ###########cookies #########################
                 session_id = 0
                 cookie = ""
                 for i in headers:
                    var, value = i.split(': ')
                    if var == 'Cookie':
                        cookietag, session_id = value.split('=')
                    if session_id not in Sessions:
                        Sessions[session_id] = {}
                 if not session_id:
                    session_id = str(generate_id())
                    Sessions[session_id] = {}
                    cookie = Cookie_string % session_id
                    print cookie
                 ############################################
                 infodic = {'headers':headers,'parameters':parameters,'new_headers':[],'session':session_id,'Sessions':Sessions}
                 print Sessions
                 ###########################################
                 if os.path.exists(ruta) and os.path.isfile(ruta):
                     x, extension = os.path.splitext(ruta)
                     if extension =='.crdm' or extension == '.rdhtml':
                        try:
                            if extension =='.crdm':
                                contenido,dict = interpret2string(open(ruta).read(),infodic)
                            else:
                                contenido,dict = interpret2string(process_file(ruta))
                            tipo = extensiones.get(extension, 'text/html')
                            ########new-headers #########
                            new_headers = dict['new_headers']
                            new_headers_string = tipo
                            for i in new_headers:
                                new_headers_string += '\n' + i
                            if cookie:
                                new_headers_string += '\n' + cookie
                            #############################
                            new_sock.send(output_header % new_headers_string + contenido)    
                        except Exception, e:
                            contenido = page500 % e
                            tipo = extensiones.get(extension, 'text/html')
                            new_sock.send(contenido)
                     else:
                        archivo = open(ruta, 'rb')
                        contenido = archivo.read()
                        archivo.close()
                        tipo = extensiones.get(extension, 'text/html')
                        new_sock.send(output_header % tipo + contenido)
                 else:
                     new_sock.send(page404)
             finally:
                 new_sock.close()
     finally:
         sock.close()           
